package com.robot.member.service;

import com.robot.member.dao.MemberDao;
import com.robot.member.pojo.Member;
import com.robot.member.pojo.vo.WeChatInfo;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import util.BinaryUtil;
import util.IdWorker;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

/**
 * member服务层
 *
 * @author wuyunbin
 */
@Service
public class MemberService {
    @Autowired
    private MemberDao memberDao;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 性别 0-女 1-男 2-未知
     */
    private String sexMale = "0";
    private String sexFemale = "1";
    private String sexUnknown = "2";
    @Value("${sys.member.avatar}")
    private String avatar;

    /**
     * 查询全部列表
     *
     * @return
     */
    public List<Member> findAll() {
        return memberDao.findAll();
    }


    /**
     * 条件查询+分页
     *
     * @param whereMap
     * @param page
     * @param size
     * @return
     */
    public Page<Member> findSearch(Map whereMap, int page, int size) {
        Specification<Member> specification = createSpecification(whereMap);
        PageRequest pageRequest = PageRequest.of(page - 1, size);
        return memberDao.findAll(specification, pageRequest);
    }


    /**
     * 条件查询
     *
     * @param whereMap
     * @return
     */
    public List<Member> findSearch(Map whereMap) {
        Specification<Member> specification = createSpecification(whereMap);
        return memberDao.findAll(specification);
    }

    /**
     * 根据ID查询实体
     *
     * @param id
     * @return
     */
    public Member findById(String id) {
        return memberDao.findById(id).orElse(null);
    }

    /**
     * 增加
     *
     * @param member
     */
    public void add(Member member) {
        if (member.getId() == null) {
            member.setId(BinaryUtil.decimal2Base62(idWorker.nextId()));
        }
        Calendar calendar = Calendar.getInstance();
        member.setYear(calendar.get(Calendar.YEAR) + "");
        member.setMonth(Calendar.MONTH + "");
        member.setDate(Calendar.DATE + "");
        member.setDay(Calendar.DAY_OF_WEEK + "");
        member.setHours(Calendar.HOUR + "");
        if (!sexMale.equals(member.getSex()) && !sexFemale.equals(member.getSex())) {
            member.setSex(sexUnknown);
        }

        if ("".equals(member.getAvatar()) || member.getAvatar() == null) {
            member.setAvatar(avatar);
        }

        member.setIsPlus("0");
        member.setRealNameStatus("0");
        member.setStatus("1");
        member.setTotalSave(new BigDecimal(0));

        LocalDateTime now = LocalDateTime.now();

        member.setCreatedAt(now);
        member.setUpdatedAt(now);
        member.setLastLoginTime(now);
        memberDao.save(member);
    }

    public Member addByWeChat(WeChatInfo weChatInfo) {
        Member member = new Member();

        LocalDateTime now = LocalDateTime.now();

        member.setId(BinaryUtil.decimal2Base62(idWorker.nextId()));
        member.setYear(now.getYear() + "");
        member.setMonth(now.getMonthValue() + "");
        member.setDate(now.getDayOfMonth() + "");
        member.setDay(now.getDayOfWeek().getValue() + "");
        member.setHours(now.getHour() + "");
        String sex = weChatInfo.getSex();
        if ("2".equals(sex)) {
            sex = "0";
        }
        member.setSex(sex);
        member.setIsPlus("0");
        member.setRealNameStatus("0");
        member.setStatus("1");
        member.setTotalSave(new BigDecimal(0));
        member.setOpenId(weChatInfo.getOpenId());
        member.setUnionId(weChatInfo.getUnionId());
        member.setAvatar(weChatInfo.getHeadImgUrl());
        member.setNickname(weChatInfo.getNickname());

        member.setCreatedAt(now);
        member.setUpdatedAt(now);
        member.setLastLoginTime(now);
        logger.info(member.toString());
        memberDao.save(member);
        return member;
    }

    public Member addByWeChat(WeChatInfo weChatInfo, String recommendId) {
        Member member = new Member();

        LocalDateTime now = LocalDateTime.now();

        member.setId(BinaryUtil.decimal2Base62(idWorker.nextId()));
        member.setYear(now.getYear() + "");
        member.setMonth(now.getMonthValue() + "");
        member.setDate(now.getDayOfMonth() + "");
        member.setDay(now.getDayOfWeek().getValue() + "");
        member.setHours(now.getHour() + "");
        String sex = weChatInfo.getSex();
        if ("2".equals(sex)) {
            sex = "0";
        }
        member.setSex(sex);
        member.setIsPlus("0");
        member.setRealNameStatus("0");
        member.setStatus("1");
        member.setTotalSave(new BigDecimal(0));
        member.setOpenId(weChatInfo.getOpenId());
        member.setUnionId(weChatInfo.getUnionId());
        member.setAvatar(weChatInfo.getHeadImgUrl());
        member.setNickname(weChatInfo.getNickname());
        member.setRecommendId(recommendId);
        member.setCreatedAt(now);
        member.setUpdatedAt(now);
        member.setLastLoginTime(now);
        logger.info(member.toString());
        memberDao.save(member);
        return member;
    }

    /**
     * 检查是否是图片
     *
     * @param src
     * @return
     */
    public String checkImage(String src) {
        String point = ".";
        int flag = 0;
        if (!src.contains(point)) {
            return "";
        }
        String suffixName = src.substring(src.lastIndexOf("."));
        String[] formatImage = {".jpg", ".jpeg", ".bmp", ".png"};
        for (String f : formatImage) {
            if (f.equals(suffixName)) {
                flag++;
            }
        }
        if (flag == 0) {
            System.out.println("不是图片");
            return "";
        }
        return suffixName;
    }


    /**
     * 修改
     *
     * @param member
     */
    public void update(Member member) {
        member.setUpdatedAt(LocalDateTime.now());
        memberDao.save(member);
    }

    /**
     * 删除
     *
     * @param id
     */
    public void deleteById(String id) {
        memberDao.deleteById(id);
    }

    /**
     * 动态条件构建
     *
     * @param searchMap
     * @return
     */
    private Specification<Member> createSpecification(Map searchMap) {
        return new Specification<Member>() {
            @Override
            public Predicate toPredicate(Root<Member> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicateList = new ArrayList<Predicate>();
                // 会员id
                String id = "id";
                if (searchMap.get(id) != null && !"".equals(searchMap.get(id))) {
                    predicateList.add(cb.like(root.get(id).as(String.class), "%" + (String) searchMap.get(id) + "%"));
                }
                // 电话
                String phone = "phone";
                if (searchMap.get(phone) != null && !"".equals(searchMap.get(phone))) {
                    predicateList.add(cb.like(root.get(phone).as(String.class), "%" + (String) searchMap.get(phone) + "%"));
                }
                // 邮箱
                String email = "email";
                if (searchMap.get(email) != null && !"".equals(searchMap.get(email))) {
                    predicateList.add(cb.like(root.get(email).as(String.class), "%" + (String) searchMap.get(email) + "%"));
                }
                // 昵称-默认取微信昵称
                String nickname = "nickname";
                if (searchMap.get(nickname) != null && !"".equals(searchMap.get(nickname))) {
                    predicateList.add(cb.like(root.get(nickname).as(String.class), "%" + (String) searchMap.get(nickname) + "%"));
                }
                // 密码
                String password = "password";
                if (searchMap.get(password) != null && !"".equals(searchMap.get(password))) {
                    predicateList.add(cb.like(root.get(password).as(String.class), "%" + (String) searchMap.get(password) + "%"));
                }
                // 是否plus会员
                String isPlus = "isPlus";
                if (searchMap.get(isPlus) != null && !"".equals(searchMap.get(isPlus))) {
                    predicateList.add(cb.like(root.get(isPlus).as(String.class), "%" + (String) searchMap.get(isPlus) + "%"));
                }
                // 性别 0-女 1-男 2-未知
                String sex = "sex";
                if (searchMap.get(sex) != null && !"".equals(searchMap.get(sex))) {
                    predicateList.add(cb.like(root.get(sex).as(String.class), "%" + (String) searchMap.get(sex) + "%"));
                }
                // 身份证号码
                String idCard = "idCard";
                if (searchMap.get(idCard) != null && !"".equals(searchMap.get(idCard))) {
                    predicateList.add(cb.like(root.get(idCard).as(String.class), "%" + (String) searchMap.get(idCard) + "%"));
                }
                // 真实姓名
                String realName = "realName";
                if (searchMap.get(realName) != null && !"".equals(searchMap.get(realName))) {
                    predicateList.add(cb.like(root.get(realName).as(String.class), "%" + (String) searchMap.get(realName) + "%"));
                }
                // 实名制状态 0-未实名 1-已实名 2-实名失败
                String realNameStatus = "realNameStatus";
                if (searchMap.get(realNameStatus) != null && !"".equals(searchMap.get(realNameStatus))) {
                    predicateList.add(cb.like(root.get(realNameStatus).as(String.class), "%" + (String) searchMap.get(realNameStatus) + "%"));
                }
                // 最后登录ip
                String lastLoginIp = "lastLoginIp";
                if (searchMap.get(lastLoginIp) != null && !"".equals(searchMap.get(lastLoginIp))) {
                    predicateList.add(cb.like(root.get(lastLoginIp).as(String.class), "%" + (String) searchMap.get(lastLoginIp) + "%"));
                }
                // 推荐人id
                String recommendId = "recommendId";
                if (searchMap.get(recommendId) != null && !"".equals(searchMap.get(recommendId))) {
                    predicateList.add(cb.like(root.get(recommendId).as(String.class), "%" + (String) searchMap.get(recommendId) + "%"));
                }
                // 推荐人名称
                String recommendName = "recommendName";
                if (searchMap.get(recommendName) != null && !"".equals(searchMap.get(recommendName))) {
                    predicateList.add(cb.like(root.get(recommendName).as(String.class), "%" + (String) searchMap.get(recommendName) + "%"));
                }
                // 微信open_id
                String openId = "openId";
                if (searchMap.get(openId) != null && !"".equals(searchMap.get(openId))) {
                    predicateList.add(cb.like(root.get(openId).as(String.class), "%" + (String) searchMap.get(openId) + "%"));
                }
                // 微信union_id
                String unionId = "unionId";
                if (searchMap.get(unionId) != null && !"".equals(searchMap.get(unionId))) {
                    predicateList.add(cb.like(root.get(unionId).as(String.class), "%" + (String) searchMap.get(unionId) + "%"));
                }
                // 注册日的年
                String year = "year";
                if (searchMap.get(year) != null && !"".equals(searchMap.get(year))) {
                    predicateList.add(cb.like(root.get(year).as(String.class), "%" + (String) searchMap.get(year) + "%"));
                }
                // 注册日的月
                String month = "month";
                if (searchMap.get(month) != null && !"".equals(searchMap.get(month))) {
                    predicateList.add(cb.like(root.get(month).as(String.class), "%" + (String) searchMap.get(month) + "%"));
                }
                // 注册日的日期
                String date = "date";
                if (searchMap.get(date) != null && !"".equals(searchMap.get(date))) {
                    predicateList.add(cb.like(root.get(date).as(String.class), "%" + (String) searchMap.get(date) + "%"));
                }
                // 注册日的星期
                String day = "day";
                if (searchMap.get(day) != null && !"".equals(searchMap.get(day))) {
                    predicateList.add(cb.like(root.get(day).as(String.class), "%" + (String) searchMap.get(day) + "%"));
                }
                // 来源
                String comeForm = "comeForm";
                if (searchMap.get(comeForm) != null && !"".equals(searchMap.get(comeForm))) {
                    predicateList.add(cb.like(root.get(comeForm).as(String.class), "%" + (String) searchMap.get(comeForm) + "%"));
                }
                // 状态 0-禁用 1-启用
                String status = "status";
                if (searchMap.get(status) != null && !"".equals(searchMap.get(status))) {
                    predicateList.add(cb.like(root.get(status).as(String.class), "%" + (String) searchMap.get(status) + "%"));
                }
                //剔除软删除数据
                String deletedAt = "deletedAt";
                predicateList.add(cb.equal(root.get(deletedAt), cb.nullLiteral(LocalDateTime.class)));

                return cb.and(predicateList.toArray(new Predicate[predicateList.size()]));
            }
        };
    }

    /**
     * 查找会员推荐人名字
     *
     * @param recommendId 推荐人id
     * @return 推荐人的nickname
     */
    public String findRecommenderName(String recommendId) {
        return memberDao.findRecommenderName(recommendId);
    }

    /**
     * 查找会员推荐人数
     *
     * @param id
     * @return
     */
    public Integer findRecommendedNumber(String id) {
        return memberDao.findRecommendedNumber(id);
    }

    /**
     * 发送订阅消息
     *
     * @param phone
     * @return
     */
    public void sendOrderMassage(String phone) {
        String checkcode = RandomStringUtils.randomNumeric(4);

        Map<String, String> map = new HashMap<>(4);
        map.put("phone", phone);
        map.put("checkCode", checkcode);
        map.put("subject", "订购成功");
        map.put("text", "尊敬的用户,您好:\n"
                + "你今天中午在本商城下单了xxx产品,金额9.9元" +
                "祝你购物愉快!");
        /**
         * 为方便测试，先不实现短信的发送，直接在后台显示
         */
        rabbitTemplate.convertAndSend("sms", map);
        /**
         * 在控制台显示一份【方便测试】
         */
        System.out.println("the phone is:" + phone + ",the checkCode is:" + checkcode + ",the<" + redisTemplate.opsForValue().get("sendSmsCount_" + phone) + ">time");
    }

    /**
     * 通过手机号查询用户
     *
     * @param phone
     * @return
     */
    public Member findByPhone(String phone) {
        return memberDao.findByPhone(phone);
    }

    /**
     * 通过openId查询用户
     *
     * @param openId
     * @return
     */
    public Member findByOpenId(String openId) {
        return memberDao.findByOpenId(openId);
    }

    /**
     * 通过recommendId查询用户列表并分页
     *
     * @param recommendId
     * @param page
     * @param size
     * @return
     */
    public Page<Member> findAllByRecommendIdOrderByCreatedAtDesc(String recommendId, int page, int size) {
        Pageable pageable = PageRequest.of(page - 1, size);
        return memberDao.findAllByRecommendIdOrderByCreatedAtDesc(recommendId, pageable);
    }

    /**
     * 后台会员列表并分页
     *
     * @param page
     * @param size
     * @return
     */
    public Page<Member> findAll(int page, int size) {
        Pageable pageable = PageRequest.of(page - 1, size);
        return memberDao.findAll(pageable);

    }

    public Member findByIdAndStatus(String id, String status) {
        return memberDao.findByIdAndStatus(id, status);
    }

    /**
     * 通过推荐人名字查询推荐列表
     *
     * @param nickname
     * @param page
     * @param size
     * @return
     */
    public Page<Member> findAllByRecommendName(String nickname, int page, int size) {
        Pageable pageable = PageRequest.of(page - 1, size);
        return memberDao.findAllByRecommendName(nickname, pageable);
    }

    /**
     * 通过推荐人手机号查询推荐列表
     *
     * @param phone
     * @param page
     * @param size
     * @return
     */
    public Page<Member> findAllByRecommendPhone(String phone, int page, int size) {
        Pageable pageable = PageRequest.of(page - 1, size);
        return memberDao.findAllByRecommendPhone(phone, pageable);
    }

    /**
     * 根据isPlus查找今日会员
     *
     * @param isPlus
     * @param page
     * @param size
     * @return
     */
    public Page<Member> findAllByIsPlusAndToday(String isPlus, int page, int size) {
        Pageable pageable = PageRequest.of(page - 1, size);
        return memberDao.findAllByIsPlusAndToday(isPlus, pageable);
    }

    /**
     * 根据isPlus查找昨天会员
     *
     * @param isPlus
     * @param page
     * @param size
     * @return
     */
    public Page<Member> findAllByIsPlusAndYesterday(String isPlus, int page, int size) {
        Pageable pageable = PageRequest.of(page - 1, size);
        return memberDao.findAllByIsPlusAndYesterday(isPlus, pageable);
    }

    /**
     * 根据isPlus查找最近7日会员
     *
     * @param isPlus
     * @param page
     * @param size
     * @return
     */
    public Page<Member> findAllByIsPlusAndWeek(String isPlus, int page, int size) {
        Pageable pageable = PageRequest.of(page - 1, size);
        return memberDao.findAllByIsPlusAndWeek(isPlus, pageable);
    }

    /**
     * 根据isPlus和时间段查找总会员
     *
     * @param isPlus
     * @param startTime
     * @param endTime
     * @param page
     * @param size
     * @return
     */
    public Page<Member> findAllByIsPlusAndBetweenAnd(String isPlus, String startTime, String endTime, int page, int size) {
        Pageable pageable = PageRequest.of(page - 1, size);
        return memberDao.findAllByIsPlusAndBetweenAnd(isPlus, startTime, endTime, pageable);
    }

    /**
     * 根据isPlus查找总会员
     *
     * @param isPlus
     * @param page
     * @param size
     * @return
     */
    public Page<Member> findAllByIsPlusAndTotal(String isPlus, int page, int size) {
        Pageable pageable = PageRequest.of(page - 1, size);
        return memberDao.findAllByIsPlusAndTotal(isPlus, pageable);
    }

    public Member findByClaims(HttpServletRequest request) {
        Claims claims = (Claims) request.getAttribute("robot_member");
        if (claims == null) {
            logger.info("claims is null");
            return null;
        }
        logger.info("claims.getId()=" + claims.getId());

        return findById(claims.getId());
    }

    public boolean checkByClaims(HttpServletRequest request) {
        Claims claims = (Claims) request.getAttribute("robot_member");
        if (claims != null) {
            return true;
        }
        return false;
    }

    public static void main(String[] args) {
        LocalDateTime now = LocalDateTime.now();
        System.out.println(now);
    }


}
